package panda.query.condition;

import java.util.ArrayList;
import java.util.List;

import panda.query.scan.Scanner;
import panda.query.struct.Attribute;
import panda.query.tree.QueryTreeNode;
import panda.transaction.Transaction;

/**
 * The propositional expression corresponding to <i>OR</i> in SQL
 * Assume the expression is a CNF 
 * @author Tian Yuan
 *
 */
public class Clause implements BooleanExpression {

	List<BooleanExpression> terms = new ArrayList<BooleanExpression>();
		
	/**
	 * 
	 */
	public Clause() {
		
	}
	
	/**
	 * 
	 * @param b
	 */
	public Clause(BooleanExpression b) {
		terms.add(b);
	}
	
	/**
	 * 
	 * @param b
	 */
	public void addClause(BooleanExpression b) {
		terms.add(b);
	}
	
	/**
	 * 
	 * @param s
	 * @return
	 */
	public int isSatisfied(Scanner s, Transaction tx) {
		boolean un = false;
		for (int i = 0; i < terms.size(); i++) {
			int res = terms.get(i).isSatisfied(s, tx);
			if (res == 1) return 1;
			if (res == 0) un = true;
		}
		if (un) return 0; else return -1;
	}

	public int equateWithConstant(Attribute attr) {
		int total = 0;
		
		for (int i = 0; i < terms.size(); i++) {
			int c = terms.get(i).equateWithConstant(attr);
			total += c;
		}
		return total;
	}

	public double reductionFactor(QueryTreeNode n) {
		double factor = terms.get(0).reductionFactor(n);
		double temp;
		for (int i = 1; i < terms.size(); i++)
			if ((temp = terms.get(0).reductionFactor(n)) < factor)
				factor = temp;
		return factor;
	}	

}
